package com.ms.yk;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.ms.yk.easypremissions.EasyPermissions;
import com.ms.yk.easypremissions.helper.PermissionHelper;

import java.util.Arrays;
import java.util.List;

public class SplashActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    private EasyPermissions.Callback callbacks;
    private AlertDialog dialog, perDialog;
    private SharedPreferences sharedPreferences;

    @Override
    public int getContentViewId() {
        return R.layout.activity_splash;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        showPermissionRequest();
    }

    private void showPermissionRequest() {
        requestPermission(new EasyPermissions.Callback() {
            @Override
            public void onGranted(int requestCode, @NonNull List<String> perms) {
                if (perms.size() < 2) {
                    return;
                }
                //悬浮窗权限判断
                if (Build.VERSION.SDK_INT >= 23) {
                    if (!Settings.canDrawOverlays(getApplicationContext())) {
                        //启动Activity让用户授权
                        setFloatWindowDialog();
                    } else {
                        sharedPreferences = getSharedPreferences("data", Context.MODE_PRIVATE);
                        boolean islogin = sharedPreferences.getBoolean("isLogin", false);
                        if (islogin) {
                            startActivity(new Intent(context, MainActivity.class));
                        } else {
                            startActivity(new Intent(context, LoginActivity.class));
                        }
                    }
                }
            }

            @Override
            public void onDenied(int requestCode, @NonNull List<String> perms) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    for (String permission :
                            perms) {
                        if (!shouldShowRequestPermissionRationale(permission)) {
                            //你自己写提醒用户的逻辑,引导用户手动去设置里开启权限
                            if (perDialog == null) {
                                perDialog = new AlertDialog.Builder(context)
                                        .setCancelable(false)
                                        .setTitle("权限未开启")//这里是表头的内容
                                        .setMessage("权限未开启无法使用")//这里是中间显示的具体信息
                                        .setPositiveButton("设置",//这个string是设置左边按钮的文字
                                                (dialog, which) -> toSelfSetting())
                                        .setNegativeButton("取消",//这个string是设置右边按钮的文字
                                                (dialog, which) -> {
                                                    finish();
                                                }).create();
                            }
                            if (!perDialog.isShowing()) {
                                perDialog.show();
                            }
                            return;
                        }
                    }
                }
            }
        }, 1000, Manifest.permission.READ_SMS, Manifest.permission.READ_EXTERNAL_STORAGE);

    }

    //提醒开启悬浮窗的弹框
    private void setFloatWindowDialog() {
        runOnUiThread(() -> {
            if (dialog == null) {
                dialog = new AlertDialog.Builder(context)
                        .setCancelable(false)
                        .setTitle("启用悬浮窗")//这里是表头的内容
                        .setMessage("为了App的稳定性，建议开启\"显示悬浮窗\"选项")//这里是中间显示的具体信息
                        .setPositiveButton("设置",//这个string是设置左边按钮的文字
                                (dialog, which) -> {
                                    try {
                                        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                                        startActivity(intent);
                                    } catch (Exception e) {
                                        Toast.makeText(context, "无法跳转到设置界面，请在权限管理中开启该应用的悬浮窗", Toast.LENGTH_SHORT).show();
                                        e.printStackTrace();
                                    }
                                })
                        .setNegativeButton("取消",//这个string是设置右边按钮的文字
                                (dialog, which) -> finish()).create();
            }
            if (!dialog.isShowing()) {
                dialog.show();
            }
        });
    }

    public void toSelfSetting() {
        Intent mIntent = new Intent();
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            mIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            mIntent.setAction(Intent.ACTION_VIEW);
            mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            mIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(mIntent);
    }

    public void requestPermission(EasyPermissions.Callback callbacks, int requestCode, @NonNull String... permissions) {
        this.callbacks = null;
        if (EasyPermissions.hasPermissions(this, permissions)) {
            if (callbacks != null) {
                callbacks.onGranted(requestCode, Arrays.asList(permissions));
            }
        } else {
            this.callbacks = callbacks;
            PermissionHelper.newInstance(this).directRequestPermissions(requestCode, permissions);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (callbacks != null) {
            callbacks.onGranted(requestCode, perms);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (callbacks != null) {
            callbacks.onDenied(requestCode, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}